package algorithm

import (
	"math/rand"
)

type Round struct {
	Start int
	End   int
}
type Hash struct {
	Choice int
	Weight int
}
type Algorithm struct {
	Hash        []Hash
	Round       map[int]Round
	TotalWeight int
}

func NewAlgorithm() *Algorithm {
	return &Algorithm{
		Round: make(map[int]Round),
	}
}

func (a *Algorithm) Add(choice, weight int) {
	h := Hash{Choice: choice, Weight: weight}
	a.Hash = append(a.Hash, h)
}
func (a *Algorithm) BaseSelect() {
	var lastR Round
	for k, h := range a.Hash {
		if h.Weight == 0 {
			continue
		}
		a.TotalWeight = a.TotalWeight + h.Weight
		if k == 0 {
			a.Round[h.Choice] = Round{
				Start: 0,
				End:   h.Weight - 1,
			}
		} else {
			a.Round[h.Choice] = Round{
				Start: lastR.End + 1,
				End:   h.Weight + lastR.End,
			}
		}
		lastR = a.Round[h.Choice]
	}
}

func (a *Algorithm) GetSelect() int {
	n := rand.Intn(a.TotalWeight)
	for k, v := range a.Round {
		if v.Start <= n && v.End >= n {
			return k
		}
	}

	return 0
}
